<?php
namespace app\api\controller;
use app\api\ApiController;
use common\bot\SteamBotService;
use common\service\AuthService;
use common\service\TradeOfferService;
use think\Request;
use common\service\UserService;
use common\service\InvService;
use think\Cache;
use common\service\LogService;

class Tradeoffer extends ApiController
{
	public $steamInfo = [];//用户steam信息

	public function __construct()
	{
		parent::__construct();
		$this->steamInfo = AuthService::getInstance()->verifyToken();
		$this->steamInfo = empty($this->steamInfo) ? [] : $this->steamInfo;
	}
	
	public function hasTradeOrder(){
		if(empty($this->steamInfo)){
			return $this->errorMessage(BAD_ACCESS_TOKEN_NO, BAD_ACCESS_TOKEN_ERROR);
		}
		$userId = $this->steamInfo['user_id'];
		if(TradeOfferService::getInstance()->lastCreatingOrder($userId)){
			return $this->successJson();
		}
		return $this->customerMessage('无交易中的订单需要确认');
	}
	

 	public function createTradeOffer($appId = 730){

 		$result = $this->validate(
 				['appId' => $appId],
 				['appId' => 'number']
 		);
 		if(true !== $result){
 			// 验证失败 输出错误信息
 			return $this->errorParams($result);
 		}
 		if(empty($this->steamInfo)){
 			return $this->errorMessage(BAD_ACCESS_TOKEN_NO, BAD_ACCESS_TOKEN_ERROR);
 		}
 		$userId = $this->steamInfo['user_id'];
 		$steamId = $this->steamInfo['steam_id'];
 		$param = Request::instance()->request();
// 		if(!UserService::getInstance()->checkTradePwd($userId, $traderPwd)){
// 			LogService::getInstance()->addActionLog(__FUNCTION__, $userId, $steamId, USER_TRANS_PWD_ERR_ERROR);
// 			return $this->errorMessage(USER_TRANS_PWD_ERR,USER_TRANS_PWD_ERR_ERROR);
// 		}

 		if(TradeOfferService::getInstance()->lastCreatingOrder($userId)){
 			LogService::getInstance()->addActionLog(__FUNCTION__, $userId, $steamId, HAS_CREATING_ORDER_ERROR);
 			return $this->errorMessage(HAS_CREATING_ORDER_NO,HAS_CREATING_ORDER_ERROR);
 		}

 		// 5分钟内有未完成则不成功
 		if(TradeOfferService::getInstance()->getDoingOrders($userId)){
            return $this->errorMessage(HAS_CREATING_ORDER_NO,HAS_CREATING_ORDER_ERROR);
        }
 		
 		$userInfo = UserService::getInstance()->getUserInfoBySteamId($steamId);
 		if(empty($userInfo['trade_off_url'])){
 			LogService::getInstance()->addActionLog(__FUNCTION__, $userId, $steamId, TRADEURL_NOTEXIST_ERROR);
 			return $this->errorMessage(TRADEURL_NOTEXIST_NO, TRADEURL_NOTEXIST_ERROR);
 		}

 		$Items = InvService::getInstance()->getUserSelectItem($steamId,array($appId));
 		if(empty($Items)){//10003
 			return $this->errorMessage(CUSTOMER_NO,'请选择物品');
 		}
 		//可以发起交易报价了
 		$createOrderStatusKey = sprintf(CREATE_ORDER_STATUS_STEAMID,$steamId);
 		$createOrderStatus = Cache::store('redis')->get($createOrderStatusKey);

 		if($createOrderStatus == 1){//报价正在进行中 直接返回
 			LogService::getInstance()->addActionLog(__FUNCTION__, $userId, $steamId, '交易报价不能频繁发起');
			return $this->errorMessage(CUSTOMER_NO,'交易报价不能频繁发起');
 		}

        Cache::store('redis')->set($createOrderStatusKey,1,300);
 		$result = TradeOfferService::getInstance()->create($this->steamInfo,$Items,$user_bank_id = 0);
 		//可以发起交易报价了
 		Cache::store('redis')->set($createOrderStatusKey,0,300);

        if(isset($result['code']) &&  $result['code'] == false){
            LogService::getInstance()->addActionLog(__FUNCTION__, $userId, $steamId, $result['message']);
            return $this->errorMessage(CREATE_TRADEOFFER_FAIL_NO,$result['message']);

        }
 		
 		if($result == -2){//30002
 			return $this->errorMessage(STEAM_INVENTORY_CHANGE_NO, STEAM_INVENTORY_CHANGE_ERROR);
 		}
 		if($result == -3){//30003
 			return $this->errorMessage(BAD_ROBOT_LOGIN_NO, BAD_ROBOT_LOGIN_ERROR);
 		}
        if($result == -4){//10003
            return $this->errorMessage(CUSTOMER_NO,'机器人烦忙');
        }
        if($result == -6){//30017
            return $this->errorMessage(CUSTOMER_NO, '您的账号已进入审核状态，请及时联系客服人员。');
        }
 		if(empty($result)){//30001
 			LogService::getInstance()->addActionLog(__FUNCTION__, $userId, $steamId, '报价发起失败,请刷新尝试');
 			return $this->errorMessage(CREATE_TRADEOFFER_FAIL_NO, CREATE_TRADEOFFER_FAIL_ERROR);
 		}

        InvService::getInstance()->resetUserInventoryStatus($steamId, $appId);
 		return $this->successJson($result);
 	}

 	/**
 	 * @api {get} /tradeoffer/checkTradeOrder 检测交易
 	 * @apiVersion 1.0.0
 	 * @apiName checkTradeOrder
 	 * @apiGroup tradeoffer
 	 *
 	 * @apiDescription    检测是否有交易中的tradeoffer
 	 *
 	 * @apiParam {String} access_token access_token
 	 *
 	 * @apiError 20000 请求参数错误
 	 *
 	 * @apiErrorExample Response (errorExample)
 	 * {
 	 *	code: 10003,
 	 *	msg: "你有未完成的交易"
 	 * }
 	 * @apiSuccessExample Response (example):
 	 *  {
 	 *		code: 99999,
 	 *		msg: "请求成功",
 	 *	}
 	 */
 	public function checkTradeOrder(){
 		$userId = $this->steamInfo['user_id'];
 		$result = TradeOfferService::getInstance()->lastCreatingOrder($userId);
 		if($result){
 			return $this->customerMessage('10003',"你有未完成的交易订单");
 		}
 		return $this->successJson();
 	}
 	
 	public function lastCreatingOrder(){
 		if(empty($this->steamInfo)){
 			return $this->errorMessage(BAD_ACCESS_TOKEN_NO,BAD_ACCESS_TOKEN_ERROR);
 		}
 		$userId = $this->steamInfo['user_id'];
 		$result = TradeOfferService::getInstance()->lastCreatingOrder($userId);
 		if($result === false){
 			return $this->errorMessage('10003');
 		}
 		return $this->successJson($result);
 	}

    /**
     * @api {get} /tradeoffer/tradeOfferDetail 交易清单
     * @apiVersion 1.0.0
     * @apiName tradeOfferDetail
     * @apiGroup tradeoffer
     *
     * @apiDescription    交易成功,展示本次交易清单
     *
     * @apiParam {String} orderNo 订单编号
     * @apiParam {int} page 页码
     * @apiParam {int} limit 页大小
     *
     * @apiError 20000 请求参数错误
     *
     * @apiSuccessExample Response (example):
     *  {
     *   "code": 99999,
     *   "msg": "请求成功",
     *   "data": {
     *   "count": 1,
     *   "limit": 20,
     *   "totalPage": 1,
     *   "currentPage": 1,
     *   "nextPage": 1,
     *   "detailList": [
     *   {
     *   "image": "",
     *   "market_hash_name": "Gamma 2 Case",
     *   "price": "0.06"
     *   }
     *   ]
     *   "orderNo":"12324314",
     *   "totalMoney":"123.22"
     *   }
     *   }
     */
    public function tradeOfferDetail($orderNo)
    {
        $user = AuthService::getInstance()->verifyToken();
        if(empty($user)){
            return $this->errorMessage(BAD_ACCESS_TOKEN_NO,BAD_ACCESS_TOKEN_ERROR);
        }
        $userId = $user['user_id'];
        $result = TradeOfferService::getInstance()->getDetail($userId, $orderNo);
        if(empty( $result )){
        	return $this->errorMessage(ORDER_IS_NO, ORDER_IS_ERROR);
        }
        return $this->successJson($result);
    }
	
    public function orderNo($orderNo = null){
    	if(empty($this->steamInfo)){
    		return $this->errorMessage(BAD_ACCESS_TOKEN_NO,BAD_ACCESS_TOKEN_ERROR);
    	}
    	$userId = $this->steamInfo['user_id'];
    	$result = TradeOfferService::getInstance()->getTradeOrderByNo($userId,$orderNo);
    	if(empty( $result )){
    		return $this->errorMessage(ORDER_IS_NO, ORDER_IS_ERROR);
    	}
    	return $this->successJson($result);
    }

    /**
     * 检测交易链接
     * @param Request $request
     */
    public function checkTradeUrl($tradeUrl = null)
    {
        $result = $this->validate(
            ['tradeUrl' => $tradeUrl],
            ['tradeUrl' => 'require']
        );
        if(true !== $result){
            // 验证失败 输出错误信息
            return $this->errorParams($result);
        }

        $result = SteamBotService::getInstance()->checkTradeUrl($tradeUrl);

        if (!$result['code']) {
            return $this->errorParams($result['message']);
        }

        return $this->successJson($result['botInfo']);
    }

    /**
     * 发送报价
     * @param Request $request
     */
    public function sendTrade($userOrderId = null)
    {
        $result = $this->validate(
            ['userOrderId' => $userOrderId],
            ['userOrderId' => 'require']
        );
        if(true !== $result){
            // 验证失败 输出错误信息
            return $this->errorParams($result);
        }

        $result = TradeOfferService::getInstance()->sendTrade($userOrderId);

        if (!$result['code']) {
            return $this->errorParams($result['message']);
        }

        return $this->successJson($result['data']);
    }

    public function fromNotice($userOrderId = NULL)
    {
        $user = AuthService::getInstance()->verifyToken();
        if(empty($user)){
            return $this->errorMessage(BAD_ACCESS_TOKEN_NO,BAD_ACCESS_TOKEN_ERROR);
        }
        $userId = $user['user_id'];

        $result = TradeOfferService::getInstance()->fromNotice($userId, $userOrderId);

        return $this->successJson($result);
    }

    public function out($appId = 730, $botInvIds = NULL)
    {
        $result = $this->validate(
            [
                'appId' => $appId,
                'botInvIds' => $botInvIds,
            ],
            [
                'appId' => 'number',
                'botInvIds' => 'require'
            ]
        );

        if(true !== $result){
            return $this->errorParams($result);
        }

        if (empty($this->steamInfo)) {
            return $this->errorMessage(BAD_ACCESS_TOKEN_NO, BAD_ACCESS_TOKEN_ERROR);
        }
        $botInvIds = explode(',', $botInvIds);

        $result = TradeOfferService::getInstance()->outTrade($this->steamInfo['user_id'], $appId, $botInvIds);
        if ($result == -1) {
            return $this->errorMessage(CUSTOMER_NO, '建议单次取出物品不要超过200个');
        } elseif ($result == -2) {
            return $this->errorMessage(CUSTOMER_NO, '有未完成的报价，请稍后');
        } elseif ($result == -3) {
            return $this->errorMessage(CUSTOMER_NO, '用户不存在');
        } elseif ($result == -4) {
            return $this->errorMessage(CUSTOMER_NO, '用户库存发生变化，请刷新');
        } elseif ($result == -5) {
            return $this->errorMessage(CUSTOMER_NO, '物品处于冻结期，暂不可取回');
        }

        return $this->successJson($result);
    }

    public function outNotice($outTradeId = NULL)
    {
        $user = AuthService::getInstance()->verifyToken();
        if(empty($user)){
            return $this->errorMessage(BAD_ACCESS_TOKEN_NO,BAD_ACCESS_TOKEN_ERROR);
        }
        $userId = $user['user_id'];

        $result = TradeOfferService::getInstance()->outNotice($userId, $outTradeId);

        return $this->successJson($result);
    }
}
